//
//  ReadBookVOrH_VC+PopGallery.m
//  KidReading
//
//  Created by telen on 16/3/8.
//  Copyright © 2016年 刘赞黄Telen. All rights reserved.
//

#import "ReadBookVOrH_VC+PopGallery.h"
#import "ConstDefine.h"
#import "ReadPageDot.h"

@interface ZoomScrollView : UIScrollView
@property(nonatomic,weak)UIView* zoomView;
@end
@implementation ZoomScrollView
@end

#pragma mark-
@interface  PopGalleryVC : UIViewController <UIScrollViewDelegate>
@property(nonatomic,strong)NSDictionary* popDict;
@property(nonatomic,strong)KoK_RectView* rectView;
@property(nonatomic,assign)NSInteger bookid;
@property(nonatomic,strong)UIScrollView *underScrollView;
@property(nonatomic,strong)NSString *pageId;
@end
@implementation PopGalleryVC
{
    UIScrollView* pageScrollView;
    UILabel* pageIndexLabel;
    ReadPageDot* pdot;
    NSDictionary *pageScrollRectDict;
}

@synthesize popDict = popInfo;
@synthesize rectView = rectview;

- (void)viewDidLoad
{
    [super viewDidLoad];
    //
    self.view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.001];
    [self performSelector:@selector(popDataProccess) withObject:nil afterDelay:0.001];
    [self performSelector:@selector(pop) withObject:nil afterDelay:0.001];
    //轻触关闭
    [self.view addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(x)]];
    //noti orientation
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarOrientationChange) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
}

- (UIImage*)getImageForm:(NSString*)uri needDecode:(BOOL)needDecode
{
    UIImage* image = nil;
    NSString* file =  [DataProcessing bookPathForBookID:self.bookid subDir:uri];
    //NSString* fileTo = [file stringByAppendingString:@".png"];
    NSData* imageData = nil;
    if (needDecode) {
        //BOOL ret = [WYCryptDES decryptFile:file toFile:fileTo withKey:__WYDEC_Code];
        //if(ret){
        //    imageData = [[NSData alloc] initWithContentsOfFile:fileTo];
        //}
        //[[NSFileManager defaultManager] removeItemAtPath:fileTo error:nil];
        imageData = [[NSData alloc] initWithContentsOfFile:file];
        imageData = [WYCryptDES decryptFileData:imageData key:__WYDEC_Code];
    }else{
        imageData = [[NSData alloc] initWithContentsOfFile:file];
    }
    if (imageData) {
        image = [[UIImage alloc] initWithData:imageData scale:2.0];
    }
    return image;
}

//计算Size 在屏幕中 1:1显示（不出屏），或者fit后的size与scale
- (CGSize)fitSize_1x1:(CGSize)size scale:(CGFloat*)scale_
{
    if (size.width == 0 || size.height == 0) {
        return size;
    }
    if (!pageScrollRectDict) {
        pageScrollRectDict = [NSMutableDictionary dictionary];
    }
    CGSize originSize = size;
    CGFloat *originScale = scale_;
    CGSize ssize = self.view.bounds.size;
    CGSize needSize = [self fitSize_1x1:size scale:scale_ ssize:ssize];
    if (ssize.width > ssize.height) {   //横
        [pageScrollRectDict setValue:NSStringFromCGSize(needSize) forKey:@"h"];
        CGSize changedSize = CGSizeMake(ssize.height, ssize.width);
        CGSize savedSize = [self fitSize_1x1:originSize scale:originScale ssize:changedSize];
        [pageScrollRectDict setValue:NSStringFromCGSize(savedSize) forKey:@"v"];
    }else {                             //竖
        [pageScrollRectDict setValue:NSStringFromCGSize(needSize) forKey:@"v"];
        CGSize changedSize = CGSizeMake(ssize.height, ssize.width);
        CGSize savedSize = [self fitSize_1x1:originSize scale:originScale ssize:changedSize];
        [pageScrollRectDict setValue:NSStringFromCGSize(savedSize) forKey:@"h"];
    }
    
//    CGFloat scale = 1;
//    if (ssize.width <= size.width && ssize.height <= size.height) {
//        size = ssize;
//        if (ssize.width/ssize.height <= size.width/size.height) {
//            scale = ssize.width/size.width;
//        }else{
//            scale = ssize.height/size.height;
//        }
//    }else if (ssize.width <= size.width) {
//        CGFloat ratio = ssize.width/size.width;
//        size = CGSizeMake(ssize.width, size.height*ratio);
//        scale = ratio;
//    }else if (ssize.height <= size.height) {
//        CGFloat ratio = ssize.height/size.height;
//        size = CGSizeMake(size.width*ratio, ssize.height);
//        scale = ratio;
//    }
//    if(scale_)*scale_ = scale;
    
    return needSize;
}
- (CGSize)fitSize_1x1:(CGSize)size scale:(CGFloat*)scale_ ssize:(CGSize)ssize {
    
    CGFloat scale = 1;
    if (ssize.width <= size.width && ssize.height <= size.height) {
        size = ssize;
        if (ssize.width/ssize.height <= size.width/size.height) {
            scale = ssize.width/size.width;
        }else{
            scale = ssize.height/size.height;
        }
    }else if (ssize.width <= size.width) {
        CGFloat ratio = ssize.width/size.width;
        size = CGSizeMake(ssize.width, size.height*ratio);
        scale = ratio;
    }else if (ssize.height <= size.height) {
        CGFloat ratio = ssize.height/size.height;
        size = CGSizeMake(size.width*ratio, ssize.height);
        scale = ratio;
    }
    if(scale_)*scale_ = scale;
    return size;
}


//计算size 强制屏幕中 fill后 size 和 scale
- (CGSize)fillsize:(CGSize)size scale:(CGFloat*)scale_
{
    if (size.width == 0 || size.height == 0) {
        return size;
    }
    //
    CGSize ssize = self.view.bounds.size;
    CGSize originSize = size;
    CGFloat *originScale = scale_;
    CGSize needSize = [self fillsize:size scale:scale_ ssize:ssize];
    if (ssize.width > ssize.height) {   //横
        [pageScrollRectDict setValue:NSStringFromCGSize(needSize) forKey:@"h"];
        CGSize changedSize = CGSizeMake(ssize.height, ssize.width);
        CGSize savedSize = [self fillsize:originSize scale:originScale ssize:changedSize];
        [pageScrollRectDict setValue:NSStringFromCGSize(savedSize) forKey:@"v"];
    }else {                             //竖
        [pageScrollRectDict setValue:NSStringFromCGSize(needSize) forKey:@"v"];
        CGSize changedSize = CGSizeMake(ssize.height, ssize.width);
        CGSize savedSize = [self fillsize:originSize scale:originScale ssize:changedSize];
        [pageScrollRectDict setValue:NSStringFromCGSize(savedSize) forKey:@"h"];
    }
    
    
//    CGFloat scale = 1;
//    //
//    if (ssize.width/ssize.height <= size.width/size.height) {
//        scale = ssize.width/size.width;
//    }else{
//        scale = ssize.height/size.height;
//    }
//    //
//    if(scale_)*scale_ = scale;
//    return CGSizeMake(size.width*scale, size.height*scale);
    return needSize;
}

- (CGSize)fillsize:(CGSize)size scale:(CGFloat*)scale_ ssize:(CGSize)ssize {
    CGFloat scale = 1;
    //
    if (ssize.width/ssize.height <= size.width/size.height) {
        scale = ssize.width/size.width;
    }else{
        scale = ssize.height/size.height;
    }
    //
    if(scale_)*scale_ = scale;
    return CGSizeMake(size.width*scale, size.height*scale);
}


//计算size强制到 ssize 的比例
- (CGSize)fillsize:(CGSize)size toSize:(CGSize)ssize scale:(CGFloat*)scale_
{
    if (size.width == 0 || size.height == 0) {
        return size;
    }
    //
    CGFloat scale = 1;
    //
    if (ssize.width/ssize.height <= size.width/size.height) {
        scale = ssize.width/size.width;
    }else{
        scale = ssize.height/size.height;
    }
    //
    if(scale_)*scale_ = scale;
    return ssize;
}

- (void)popDataProccess
{
    //__weak ReadPagePopView* wself = self;
    if (rectview && popInfo) {
        NSDictionary* pop = popInfo;
        NSString* status = pop[@"status"];
        nullToNil(status);
        BOOL status_valid = [status isEqualToString:@"valid"];
        if (status_valid) {
            NSString* ecodetype = pop[@"encode_type"];
            nullToNil(ecodetype);
            BOOL needDecode = [ecodetype isEqualToString:@"normal"];
            NSString* mode = pop[@"mode"];
            nullToNil(mode);
            BOOL mode1_1 = [mode isEqualToString:@"1:1"];
            NSArray* source = pop[@"source"];
            nullToNil(source);
            
            //
            if (source && source.count > 0)  {
                //
                NSDictionary* dic = source.firstObject;
                NSString* htype = dic[@"type"];
                nullToNil(htype);
                NSArray* uris = dic[@"uri"];
                nullToNil(uris);
                NSInteger underIndex = 0;   //记录underScrollView当前页码
                __weak PopGalleryVC *wself = self;
                for (int i = 0; i< uris.count; i++) {
                    NSString* uri = uris[i];
                    if (![uri isKindOfClass:[NSString class]]) {
                        uri = nil;
                        NSLog(@"Error uri is Not NSString");
                    }
                    if ([htype isEqualToString:@"gallery"] && uri) {
                        UIImage* image = [self getImageForm:uri needDecode:needDecode];
                        if (pageScrollView == nil) {
                            CGFloat scale = 1;
                            CGSize pageSize = [self fitSize_1x1:image.size scale:&scale];
                            if (!mode1_1) {
                                CGFloat tempScale = 1;
                                pageSize = [self fillsize:pageSize scale:&tempScale];
                                scale *= tempScale;
                            }
                            pageScrollView = [[UIScrollView alloc] initWithFrame:CGRectZero];
                            //pageScrollView.frame = TLRectMakeCenterSize(self.view.center, pageSize);
                            [self.view addSubview:pageScrollView];
                            
                            [pageScrollView JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
                                make.size.JRMAS_equalTo(pageSize);
                                make.center.equalTo(wself.view);
                            }];
                            [pageScrollView layoutIfNeeded];
                            pageScrollView.pagingEnabled = YES;
                            pageScrollView.contentSize = CGSizeMake(pageSize.width*uris.count, pageSize.height);
                            [pageScrollRectDict setValue:uris forKey:@"uris"];
                            pageScrollView.hidden = YES;
                            pageScrollView.delegate = self;
                            if (self.underScrollView) {
                                underIndex = self.underScrollView.contentOffset.x/self.underScrollView.width;
                                if (underIndex >= uris.count) {
                                    underIndex = 0;
                                }
                                pageScrollView.contentOffset = CGPointMake(underIndex*pageScrollView.width, 0);
                            }
                        }
                        //
                        CGFloat scale = 1;
                        CGSize pageSize = pageScrollView.bounds.size;
                        [pageScrollRectDict setValue:image forKey:@(i).description];
                        [self fillsize:image.size toSize:pageSize scale:&scale];
                        //
                        if (pageSize.width >0 && pageSize.height > 0) {
                            ZoomScrollView* zoomView = [[ZoomScrollView alloc] initWithFrame:TLRectMakeOriginSize(CGPointMake(pageSize.width*i, 0), pageSize)];
                            [pageScrollView addSubview:zoomView];
                            zoomView.contentSize = pageSize;
                            zoomView.tag = i;
                            //
                            UIImageView* imgv = [[UIImageView alloc] initWithFrame:zoomView.bounds];//[[UIImageView alloc] initWithFrame:TLRectMakeOriginSize(CGPointZero, pageSize)];
                            imgv.image = image;
                            imgv.contentMode = UIViewContentModeScaleAspectFit;
                            imgv.tag = i;
                            [zoomView addSubview:imgv];
                            //
                            scale = 1/scale;
                            if(scale < 1) scale = 1;
                            zoomView.delegate = self;
                            zoomView.zoomView = imgv;
                            [zoomView setMinimumZoomScale:1];
                            [zoomView setMaximumZoomScale:scale];
                            [zoomView setZoomScale:1];
                            //
                        }
                    }
                }
                //
                CGFloat ratio = [DataProcessing shareSingle].ratio_w;
                CGFloat pod = 30/ratio;
                CGFloat wh = 50/ratio;
                CGPoint trpt = CGPointMake(pod, pod);
                pageIndexLabel = [[UILabel alloc] initWithFrame:TLRectMakeTLSize(trpt, CGSizeMake(wh, wh))];
                pageIndexLabel.backgroundColor = [UIColor lightGrayColor];
                pageIndexLabel.font = [UIFont boldSystemFontOfSize:wh*0.4];
                pageIndexLabel.textColor = [UIColor whiteColor];
                pageIndexLabel.layer.cornerRadius = wh*0.5;
                pageIndexLabel.layer.masksToBounds = YES;
                pageIndexLabel.textAlignment = NSTextAlignmentCenter;
                [self.view addSubview:pageIndexLabel];
                pageIndexLabel.text = [NSString stringWithFormat:@"%@/%@",@((underIndex+1)),@(round(pageScrollView.contentSize.width/pageScrollView.width))];
                pageIndexLabel.hidden = YES;
                //
                //
                //pdot = [[ReadPageDot alloc] initWithFrame:CGRectMake(0, self.view.height-30/[DataProcessing shareSingle].ratio_w, self.view.width,20/[DataProcessing shareSingle].ratio_w)];
                pdot = [[ReadPageDot alloc] initWithFrame:CGRectZero];
                [self.view addSubview:pdot];
                CGFloat dotBottom = 30/[DataProcessing shareSingle].ratio_w;
                CGFloat dotH = 20/[DataProcessing shareSingle].ratio_w;
                [pdot JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
                    make.left.equalTo(wself.view);
                    make.width.equalTo(wself.view);
                    make.height.JRMAS_equalTo(dotH);
                    make.bottom.equalTo(wself.view).offset(-dotBottom);
                }];
                [pdot layoutIfNeeded];
                pdot.count = uris.count;
                pdot.wh_value = 12/[DataProcessing shareSingle].ratio_w;
                pdot.imageCurrent = [UIImage imageNamed:@"page_icon_dot_black.png"];
                pdot.imageNormal = [UIImage imageNamed:@"page_icon_dot_white.png"];
                pdot.readPageDotPt = ReadPageDot_center;
                [pdot updateToIndex:underIndex];
                [pdot autoChangeSign_For:pageScrollView];
                //
                //
                CGFloat podwh = pod;
                CGFloat _fontSize = 20/ratio;
                UIButton* doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
                doneButton.userInteractionEnabled = NO;
                [doneButton setTitle:NSLocalizedString(@"close", nil) forState:UIControlStateNormal];
                //[doneButton setTitle:@"完成" forState:UIControlStateNormal];
                doneButton.titleLabel.font = [UIFont systemFontOfSize:_fontSize];
                doneButton.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
                [doneButton sizeToFit];
                doneButton.frame = CGRectInset(doneButton.frame, -8, +2);
                doneButton.layer.borderWidth = 2;
                doneButton.layer.cornerRadius = 4;
                doneButton.layer.borderColor = [UIColor whiteColor].CGColor;
                doneButton.center = CGPointMake(self.view.bounds.size.width - doneButton.bounds.size.width/2 - podwh, doneButton.bounds.size.height/2 + podwh);
                doneButton.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleBottomMargin;
                [self.view addSubview:doneButton];
            }
        }
    }
}

- (UIView *)viewForZoomingInScrollView:(ZoomScrollView *)scrollView
{
    return scrollView.zoomView;
}

- (void)scrollViewDidEndZooming:(ZoomScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale
{
    [scrollView setZoomScale:scale animated:NO];
    [self scrollViewDidZoom:scrollView];
}

- (void)scrollViewDidZoom:(ZoomScrollView *)scrollView
{
    if (scrollView.zoomScale < 1.01) {
        scrollView.zoomView.center = CGPointMake(scrollView.frame.size.width*0.5, scrollView.frame.size.height*0.5);
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (![scrollView isKindOfClass:[ZoomScrollView class]]) {
        CGPoint offset = scrollView.contentOffset;
        pageIndexLabel.text = [NSString stringWithFormat:@"%@/%@",@(floor((offset.x+pageScrollView.width*0.5)/pageScrollView.width)+1),@(round(pageScrollView.contentSize.width/pageScrollView.width))];
        CGFloat underX = 0;
        if (offset.x) {
            underX = offset.x/scrollView.width*self.underScrollView.width;
        }
        [self.underScrollView scrollRectToVisible:CGRectMake(underX, 0, self.underScrollView.width, self.underScrollView.height) animated:NO];
    }
}

- (void)statusBarOrientationChange {
    UIInterfaceOrientation orienta = [[UIApplication sharedApplication] statusBarOrientation];
    NSArray *uris = [pageScrollRectDict valueForKey:@"uris"];
    [DataProcess do_Main_quick:^{
        NSInteger currentIndex = pdot.currentIndex;
        CGSize pageSize = pageScrollView.size;
        if ((orienta==UIInterfaceOrientationLandscapeLeft || orienta==
             UIInterfaceOrientationLandscapeRight)&& [pageScrollRectDict valueForKey:@"h"]) {
            pageSize = CGSizeFromString([pageScrollRectDict valueForKey:@"h"]);
        }else if (orienta==UIInterfaceOrientationPortrait && [pageScrollRectDict valueForKey:@"v"]) {
            pageSize = CGSizeFromString([pageScrollRectDict valueForKey:@"v"]);
        }
        [pageScrollView JRMAS_updateConstraints:^(JRMASConstraintMaker *make) {
            make.size.JRMAS_equalTo(pageSize);
        }];
        [pageScrollView layoutIfNeeded];
        pageScrollView.contentSize = CGSizeMake(pageSize.width*uris.count, pageSize.height);
        for (UIView *subView in pageScrollView.subviews) {
            CGFloat originX = subView.x;
            if ([subView isKindOfClass:[ZoomScrollView class]]) {
                if (originX!=0) {
                    CGFloat originW = subView.width;
                    CGFloat xOff = (pageSize.width - originW)*subView.tag;
                    CGFloat changedX = originX + xOff;
                    [subView setX:changedX];
                }
                subView.size = pageSize;
                ZoomScrollView *zoomSubV = (ZoomScrollView *)subView;
                zoomSubV.contentSize = pageSize;
                CGFloat scale = 1;
                [zoomSubV setZoomScale:1];
                for (UIView *imgSubView in zoomSubV.subviews) {
                    if ([imgSubView isKindOfClass:[UIImageView class]]) {
                        //UIImageView *imgV = (UIImageView *)imgSubView;
                        UIImage *img = [pageScrollRectDict valueForKey:@(imgSubView.tag).description];
                        [self fillsize:img.size toSize:pageSize scale:&scale];
                        imgSubView.frame = zoomSubV.bounds;
                        //imgV.image = img;
                    }
                }
                scale = 1/scale;
                if(scale < 1) scale = 1;
                [zoomSubV setMinimumZoomScale:1];
                [zoomSubV setMaximumZoomScale:scale];
                [zoomSubV setZoomScale:1];
            }
        }
        [pageScrollView setContentOffset:CGPointMake(pageSize.width*currentIndex, 0)];
        [pdot updateToIndex:currentIndex];
        pageIndexLabel.text = [NSString stringWithFormat:@"%@/%@",@(currentIndex+1),@(uris.count)];
    }];
    //NSLog(@"--orienta--%ld",(long)orienta);
}

#pragma mark-

- (void)pop
{
    CGPoint center = pageScrollView.center;
    pageScrollView.hidden = pageIndexLabel.hidden = NO;
    pageScrollView.alpha = pageIndexLabel.alpha = pdot.alpha = 0.001f;
    pageScrollView.transform = CGAffineTransformMakeScale(0.001f, 0.001f);
    pageScrollView.center = [self.view convertPoint:self.rectView.center fromView:self.rectView.superview];
    [UIView animateWithDuration:0.3 animations:^{
        pageScrollView.transform = CGAffineTransformMakeScale(1, 1);
        pageScrollView.alpha = pageIndexLabel.alpha = pdot.alpha = 1.f;
        pageScrollView.center = center;
        self.view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.8];
    } completion:^(BOOL finished) {
    }];
}

- (void)x
{
    [UIView animateWithDuration:0.3 animations:^{
        pageScrollView.alpha = pageIndexLabel.alpha = pdot.alpha = 0.001f;
        pageScrollView.transform = CGAffineTransformMakeScale(0.001f, 0.001f);
        pageScrollView.center = [self.view convertPoint:self.rectView.center fromView:self.rectView.superview];
        self.view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.001];
    } completion:^(BOOL finished) {
        //Pep统计: Gallerry结束
        [self _x];
        NSString *pageStr = self.pageId;
        NSArray *sourceArr = [self.rectView.hot_adv_popup valueForKey:@"source"];
        NSDictionary *sourceDcit =sourceArr[0];
        NSArray *uri = [sourceDcit valueForKey:@"uri"];
        NSString *uriStr = [uri[0] lastPathComponent];
        NSString *type = [[uriStr componentsSeparatedByString:@"."] lastObject];
        if (pageStr && uriStr && type) {
            ReadBookVOrH_VC* rvc = [ReadBookVOrH_VC currentReadInstance];
            NSMutableDictionary *opDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"gallery",@"op",@(self.bookid).description,@"bid",pageStr,@"pg",@(1).description,@"opc",uriStr,@"fnm",type,@"ext", nil];
            if (self.rectView.src_id) {
                [opDict setValue:self.rectView.src_id forKey:@"resid"];
            }
            [NSObject msgToTarget:rvc menthed:@"pepSatisticSrouce_read:isBegin:" refs:@[opDict,@(NO)] needReturnValue:NO];
        }
    }];
}

- (void)_x
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
    [[ReadBookVOrH_VC currentReadInstance] dismissPopWindow];
    [self.view removeFromSuperview];
    [self removeFromParentViewController];
}

@end

@implementation ReadBookVOrH_VC (PopGallery)

- (void)popGallery:(NSDictionary*)popDict followView:(KoK_RectView*)rectview pageId:(NSString *)pageId
{
    PopGalleryVC* vc = [[PopGalleryVC alloc] init];
    vc.popDict = popDict;
    vc.rectView = rectview;
    vc.bookid = self.bookid;
    vc.pageId = pageId;
    vc.underScrollView = rectview.gallerrySV;
    vc.view.frame = self.view.bounds;
    if (self.popWindow.rootViewController) {
        [self.popWindow.rootViewController addChildViewController:vc];
        [self.popWindow.rootViewController.view addSubview:vc.view];
    }else {
        [self addChildViewController:vc];
        [self.view addSubview:vc.view];
    }
}

@end
